<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>在线考试</span>
        <span v-if="testStatus === 'ongoing'" style="float: right; color: #E6A23C;">
          <i class="el-icon-time"></i> 倒计时: {{ formattedTime }}
        </span>
      </div>

      <!-- 考试选择 -->
      <div v-if="testStatus === 'not_started'" class="text-center">
        <h2>选择你的考试类型</h2>
        <el-row :gutter="20" style="margin-top: 30px;">
            <el-col :span="8">
                <el-card shadow="hover" class="test-type-card" @click.native="startNewTest('pre_sales')">
                    <div class="card-content">
                        <i class="el-icon-sell card-icon" style="color: #409EFF;"></i>
                        <h3>售前测试</h3>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" class="test-type-card" @click.native="startNewTest('in_sales')">
                     <div class="card-content">
                        <i class="el-icon-shopping-cart-2 card-icon" style="color: #67C23A;"></i>
                        <h3>售中测试</h3>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" class="test-type-card" @click.native="startNewTest('after_sales')">
                     <div class="card-content">
                        <i class="el-icon-s-tools card-icon" style="color: #E6A23C;"></i>
                        <h3>售后测试</h3>
                    </div>
                </el-card>
            </el-col>
        </el-row>
      </div>

      <!-- 考试中 -->
      <div v-if="testStatus === 'ongoing'">
        <div v-for="(question, index) in questions" :key="question.id" class="question-item">
          <h4>
            <el-tag size="mini" :type="getQuestionTypeTag(question.questionType)" style="margin-right: 10px;">{{ formatQuestionType(question.questionType) }}</el-tag>
            {{ index + 1 }}. {{ question.question }}
            <span style="float: right; color: #909399;">{{ question.score }}分</span>
          </h4>
          <!-- 单选题 -->
          <el-radio-group v-if="question.questionType === 'multiple_choice' || !question.questionType" 
            :value="getUserAnswer(question.id)"
            @input="setUserAnswer(question.id, $event)">
            <el-radio
              v-for="(text, key) in parseOptions(question.options)"
              :key="key"
              :label="key"
              class="option-radio">
              {{ key }}. {{ text }}
            </el-radio>
          </el-radio-group>
          <!-- 多选题 -->
           <el-checkbox-group v-if="question.questionType === 'multiple_select'" 
            :value="getUserAnswer(question.id)"
            @input="setUserAnswer(question.id, $event)">
            <el-checkbox
              v-for="(text, key) in parseOptions(question.options)"
              :key="key"
              :label="key"
              class="option-checkbox">
              {{ key }}. {{ text }}
            </el-checkbox>
          </el-checkbox-group>
          <!-- 判断题 -->
          <el-radio-group v-if="question.questionType === 'true_false'" 
            :value="getUserAnswer(question.id)"
            @input="setUserAnswer(question.id, $event)">
            <el-radio label="T" class="option-radio">正确</el-radio>
            <el-radio label="F" class="option-radio">错误</el-radio>
          </el-radio-group>
          <!-- 问答题 -->
          <el-input v-if="question.questionType === 'essay'" 
            :value="getUserAnswer(question.id)"
            @input="setUserAnswer(question.id, $event)"
            type="textarea" 
            :rows="4" 
            placeholder="请输入你的答案..." 
            class="essay-textarea" />
        </div>
        <div style="text-align: center; margin-top: 30px;">
          <el-button type="success" @click="submitForGrading">提交试卷</el-button>
        </div>
      </div>

      <!-- 考试结果 -->
      <div v-if="testStatus === 'finished'">
        <div class="text-center">
        <h2>考试完成!</h2>
          <el-progress type="circle" :percentage="scorePercentage" :width="150" style="margin: 20px 0;" :color="getScoreColor()"></el-progress>
          <h3>你的分数是: {{ totalScore }} / {{ maxScore }} ({{ scorePercentage.toFixed(1) }}%)</h3>
          <h4 :style="{ color: getGradeColor() }">{{ getGradeText() }}</h4>
        <p>共 {{ questions.length }} 题, 答对 {{ correctCount }} 题。</p>
        <el-button type="primary" @click="resetTest">再考一次</el-button>
        </div>
        
        <!-- 答案展示区域 -->
        <div v-if="questionsWithAnswers.length > 0" class="answers-display" style="margin-top: 30px;">
          <h3 style="text-align: center; margin-bottom: 20px;">正确答案</h3>
          <div v-for="(question, index) in questionsWithAnswers" :key="question.id" class="answer-item">
            <div class="question-header">
              <el-tag size="mini" :type="getQuestionTypeTag(question.questionType)" style="margin-right: 10px;">
                {{ formatQuestionType(question.questionType) }}
              </el-tag>
              <span class="question-number">{{ index + 1 }}.</span>
              <span class="question-text">{{ question.question }}</span>
              <span class="question-score">{{ question.score }}分</span>
            </div>
            
            <div class="answer-content">
              <!-- 单选和多选题显示选项答案 -->
              <div v-if="question.questionType === 'multiple_choice' || question.questionType === 'multiple_select'">
                <strong>正确答案：</strong>
                <span class="correct-answer">{{ question.answer }}</span>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="question.questionType === 'true_false'">
                <strong>正确答案：</strong>
                <span class="correct-answer">{{ question.answer === 'T' ? '正确' : '错误' }}</span>
              </div>
              
              <!-- 问答题 -->
              <div v-else-if="question.questionType === 'essay'">
                <strong>参考答案：</strong>
                <div class="essay-answer">{{ question.answer || '暂无参考答案' }}</div>
              </div>
            </div>
          </div>
        </div>
        
      </div>

    </el-card>

  </div>
</template>

<script>
import { startTest, submitTest, getTestAnswers } from '@/api/system/training';

const TOTAL_TIME = 60 * 60; // 总考试时间，秒 (例如60分钟)

export default {
  name: "TrainingTest",
  data() {
    return {
      testStatus: 'not_started', // not_started, ongoing, finished
      selectedTestType: '',
      questions: [],
      userAnswers: {},
      timer: null,
      timeRemaining: TOTAL_TIME,
      totalScore: 0,
      maxScore: 0,
      scorePercentage: 0,
      correctCount: 0,
      startTime: null,
      questionsWithAnswers: [], // 带完整答案的题目列表
    };
  },
  computed: {
    formattedTime() {
      const minutes = Math.floor(this.timeRemaining / 60);
      const seconds = this.timeRemaining % 60;
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },
  },
  methods: {
    startNewTest(type) {
      this.selectedTestType = type;
      if (!this.selectedTestType) return;
      startTest(this.selectedTestType).then(response => {
        this.questions = response.data;
        // 计算总分
        this.maxScore = this.questions.reduce((sum, q) => sum + (q.score || 5), 0);
        
        // 初始化答案容器 - 使用Object.assign确保响应式
        const initialAnswers = {};
        this.questions.forEach(q => {
          if (q.questionType === 'multiple_select') {
            initialAnswers[q.id] = [];
          } else {
            initialAnswers[q.id] = '';
          }
        });
        this.userAnswers = Object.assign({}, initialAnswers);

        this.timeRemaining = TOTAL_TIME;
        this.testStatus = 'ongoing';
        this.startTime = new Date();
        this.startTimer();
      });
    },
    startTimer() {
      this.timer = setInterval(() => {
        this.timeRemaining--;
        if (this.timeRemaining <= 0) {
          clearInterval(this.timer);
          this.$modal.msgWarning("时间到，已自动提交试卷！");
          this.submitForGrading();
        }
      }, 1000);
    },
    parseOptions(optionsStr) {
      try {
        return JSON.parse(optionsStr);
      } catch (e) {
        return {};
      }
    },
    submitForGrading() {
      clearInterval(this.timer);

          const testRecord = {
              testType: this.selectedTestType,
              totalQuestions: this.questions.length,
              userAnswers: JSON.stringify(this.userAnswers),
          startTime: this.formatDateForBackend(this.startTime),
      };
      
      // 提交到后端进行评分
      submitTest(testRecord).then(response => {
        if (response.code === 200) {
          // 从后端获取评分结果
          const result = response.data;
          this.totalScore = result.score || 0;
          this.correctCount = result.correctQuestions || 0;
          this.scorePercentage = this.maxScore > 0 ? (this.totalScore / this.maxScore) * 100 : 0;
          
          // 设置完成状态
          this.testStatus = 'finished';
          
          // 获取完整的答案信息用于展示
          this.fetchAnswersForDisplay();
        } else {
          this.$modal.msgError('提交考试失败：' + response.msg);
        }
      }).catch(error => {
        this.$modal.msgError('提交考试失败');
        console.error('提交考试错误:', error);
      });
    },
    resetTest() {
        this.testStatus = 'not_started';
        this.selectedTestType = '';
        this.questions = [];
        this.userAnswers = {};
        this.totalScore = 0;
        this.maxScore = 0;
        this.scorePercentage = 0;
        this.correctCount = 0;
        this.questionsWithAnswers = [];
    },
    // 获取答案用于展示
    fetchAnswersForDisplay() {
      getTestAnswers(this.selectedTestType).then(response => {
        if (response.code === 200 && response.data) {
          this.questionsWithAnswers = response.data;
        }
      }).catch(error => {
        console.error('获取答案失败:', error);
      });
    },
    formatQuestionType(type) {
        if (type === 'true_false') return '判断题';
        if (type === 'multiple_select') return '多选题';
        if (type === 'multiple_choice') return '单选题';
        if (type === 'essay') return '问答题';
        return '单选题'; // 默认
    },
    getQuestionTypeTag(type) {
        if (type === 'true_false') return 'info';
        if (type === 'multiple_select') return 'success';
        if (type === 'multiple_choice') return 'primary';
        if (type === 'essay') return 'warning';
        return 'primary'; // 默认
    },
    getGradeText() {
        if (this.scorePercentage < 60) return '不及格';
        if (this.scorePercentage < 70) return '及格';
        if (this.scorePercentage < 80) return '良好';
        return '优秀';
    },
    getGradeColor() {
        if (this.scorePercentage < 60) return '#F56C6C';
        if (this.scorePercentage < 70) return '#E6A23C';
        if (this.scorePercentage < 80) return '#67C23A';
        return '#409EFF';
    },
    getScoreColor() {
        if (this.scorePercentage < 60) return '#F56C6C';
        if (this.scorePercentage < 70) return '#E6A23C';
        if (this.scorePercentage < 80) return '#67C23A';
        return '#409EFF';
    },
    formatDateForBackend(date) {
        if (!date) return null;
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        const hours = String(d.getHours()).padStart(2, '0');
        const minutes = String(d.getMinutes()).padStart(2, '0');
        const seconds = String(d.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 安全获取用户答案
    getUserAnswer(questionId) {
      return this.userAnswers[questionId] || (this.userAnswers[questionId] === 0 ? 0 : '');
    },
    // 安全设置用户答案
    setUserAnswer(questionId, value) {
      this.$set(this.userAnswers, questionId, value);
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
}
.question-item {
  margin-bottom: 25px;
}
.option-radio {
  display: block;
  margin: 10px 0;
}
.option-checkbox {
  display: block;
  margin: 10px 0;
}
.essay-textarea {
  margin-top: 10px;
}
.test-type-card {
    cursor: pointer;
    transition: all 0.3s ease;
}
.test-type-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.card-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 150px;
}
.card-icon {
    font-size: 48px;
    margin-bottom: 20px;
}

/* 答案展示样式 */
.answers-display {
    text-align: left;
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
}

.answer-item {
    background: white;
    padding: 15px;
    margin-bottom: 15px;
    border-radius: 6px;
    border-left: 4px solid #409EFF;
}

.question-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-weight: bold;
}

.question-number {
    margin-right: 8px;
    color: #409EFF;
}

.question-text {
    flex: 1;
    margin-right: 10px;
}

.question-score {
    color: #909399;
    font-size: 12px;
}

.answer-content {
    padding-left: 20px;
    color: #606266;
}

.correct-answer {
    color: #67C23A;
    font-weight: bold;
    background: #f0f9ff;
    padding: 2px 6px;
    border-radius: 4px;
}

.essay-answer {
    background: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    margin-top: 5px;
    min-height: 40px;
    line-height: 1.5;
}

</style> 